package com.pansoft.openplanet.activity.child;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.efounder.chat.activity.MobileShareActivity;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.SystemShareHelper;
import com.efounder.chat.zxing.qrcode.QRCode;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.struct.IMStruct002;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.activity.TCBaseActivity;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.blockchain.cypto.ec.EosPrivateKey;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.EosNetParamUtil;
import com.pansoft.openplanet.util.EosPublicAndPrivateKeyUtils;
import com.pansoft.openplanet.util.TCAccountManager;
import com.pansoft.openplanet.widget.PassWordAlertDialog;
import com.pansoft.openplanet.widget.TCLoadingDataView;
import com.utilcode.util.JFStringUtil;
import com.utilcode.util.LogUtils;
import com.utilcode.util.SizeUtils;
import com.utilcode.util.TimeUtils;
import com.utilcode.util.ToastUtils;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 创建EOS账户，公钥私钥地址存本地，服务器，未激活账户
 */
public class CreateEosWalletActivity extends TCBaseActivity {

    private ImageView ivQrCode;
    private TextView tvOwnerKey;
    private TextView tvActiveKey;
    private Button tvCreateWallet;
    private Button btnSendToFriend;
    private TextView tvHint;
    private EditText etAccountName;
    private TextView tvNameCheck;
    private ScrollView scrollContent;

    private String walletName;
    private String walletAvatar;
    private String accountName = "";
    private String mAccount_active_public_key;
    private String mAccount_owner_public_key;
    private boolean hasInactive = false;

    private AccountDao accountDao;
    private Account account;
    private boolean clickable = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_activity_create_eos);
        accountDao = new AccountDao(CreateEosWalletActivity.this);
        initIntent();
        initView();
        createEOSWallet();
        if (!hasInactive) {
            showPassDialog();
        } else {
            tvHint.setText(getString(R.string.create_eos_hint_two));
        }
    }

    private void initIntent() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            if (bundle.containsKey("active_pub_key")){
                hasInactive = true;
                mAccount_active_public_key = bundle.getString("active_pub_key");
            }
            walletName = bundle.getString("wallet_name");
            walletAvatar = bundle.getString("wallet_avatar");

        }
    }

    private void initView() {

        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(ResStringUtil.getString(R.string.open_planet_create_eos));
        ivQrCode = (ImageView) findViewById(R.id.iv_qr_code);
        tvOwnerKey = (TextView) findViewById(R.id.tv_owner_key);
        tvActiveKey = (TextView) findViewById(R.id.tv_active_key);
        tvCreateWallet = (Button) findViewById(R.id.tv_create_wallet);
        etAccountName = (EditText) findViewById(R.id.et_account_name);
        tvNameCheck = (TextView) findViewById(R.id.tv_name_check);
        scrollContent = (ScrollView) findViewById(R.id.scroll_content);
        tvHint = (TextView) findViewById(R.id.tv_hint);
        btnSendToFriend = (Button) findViewById(R.id.tv_send_to_friend);
        btnSendToFriend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clickable) {
                    sendToFriend();
                }else {
                    ToastUtils.showShort(getString(R.string.account_name_check_hint));
                }
            }
        });
        etAccountName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                accountName = etAccountName.getText().toString();
                if (accountName.equals("") ||JFStringUtil.isEosName(accountName)) {
                    clickable = true;
                    tvNameCheck.setVisibility(View.GONE);
                    setQRCode(mAccount_active_public_key, mAccount_owner_public_key);
                    //更新账户地址
                    //用来存放临时的账户名
                    accountName = etAccountName.getText().toString();
                    account.setEosTempName(accountName);
                    accountDao.insertOrReplace(account);
                } else {
                    tvNameCheck.setVisibility(View.VISIBLE);
                    clickable = false;
                }
            }
        });
        tvCreateWallet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clickable) {
                    shareImage();
                } else {
                    ToastUtils.showShort(getString(R.string.account_name_check_hint));
                }

            }
        });
    }

    private void setQRCode(String activeKey, String ownerKey) {
        Map<String, String> map = new HashMap();
        map.put("type", "createEosAccount");
        map.put("eosAccountName", accountName);
        map.put("eosActivePublicKey", activeKey);
        map.put("eosOwnerPublicKey", ownerKey);
        LogUtils.d(new JSONObject(map).toString());
        tvActiveKey.setText(activeKey);
        tvOwnerKey.setText(ownerKey);
        Bitmap bitmap = QRCode.setQRcode(new JSONObject(map).toString(), SizeUtils.dp2px(150), SizeUtils.dp2px(150));
        ivQrCode.setImageBitmap(bitmap);
    }


    private void createEOSWallet() {

        if (hasInactive) {
            // FIXME: 18-7-31
            account = accountDao.getEosAccountByActivePublicKey(mAccount_active_public_key);
            accountName = account.getEosTempName();
            etAccountName.setText(accountName);
            etAccountName.setSelection(accountName.length());
            mAccount_owner_public_key = account.getPublicKey();
            setQRCode(mAccount_active_public_key, mAccount_owner_public_key);
        } else {
            showLoading(ResStringUtil.getString(R.string.open_planet_iscreateing));
            try {
                CommonThreadPoolUtils.execute(new Runnable() {
                    @Override
                    public void run() {
                        //没有未激活账户，则新建账号
                        EosPrivateKey mOwnerKey = EosPublicAndPrivateKeyUtils.getPrivateKey(2)[0];
                        EosPrivateKey mActiveKey = EosPublicAndPrivateKeyUtils.getPrivateKey(2)[1];
                        mAccount_owner_public_key = mOwnerKey.getPublicKey().toString();
                        final String mAccount_owner_private_key = mOwnerKey.toString();
                        mAccount_active_public_key = mActiveKey.getPublicKey().toString();
                        final String mAccount_active_private_key = mActiveKey.toString();

                        //加密保存数据库
                        String secretOwnPrivatekey = TCAccountManager.encryptByMainPrivKey(mAccount_owner_private_key);
                        String secretActivePrivatekey = TCAccountManager.encryptByMainPrivKey(mAccount_active_private_key);
                        //时间戳作为临时的地址
                        String randomAddress = String.valueOf(TimeUtils.getNowMills());
                        account = new Account(randomAddress, walletName, walletAvatar);
                        account.setFileName(null);
                        account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                        account.setSecretPrivateKey(secretOwnPrivatekey);
                        account.setPublicKey(mAccount_owner_public_key);
                        account.setEosActivePubKey(mAccount_active_public_key);
                        account.setEosActivePriKey(secretActivePrivatekey);
                        account.setEosAccountNames("");
                        account.setMaster(false);
                        account.setCurrentShow(false);
                        account.setActivate(false);
                        account.setAccountType(Account.ACCOUNT_TYPE_COMMON);
                        //用来存放临时的账号名
                        account.setEosTempName(accountName);
                        account.setBlockChainName(EosNetParamUtil.getEosChainName());
                        account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress", ""));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setQRCode(mAccount_active_public_key, mAccount_owner_public_key);
                                LogUtils.d(mAccount_owner_public_key, mAccount_owner_private_key, mAccount_active_public_key, mAccount_active_private_key);
                                dismissLoading();
                            }
                        });
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                dismissLoading();
                ToastUtils.showShort(R.string.open_planet_create_wallet_fail);
            }
        }

    }

//    private void showEOSCreateSuccessDialog(final String privateKey, final Account account) {
//        dismissLoading();
//        final ExportPrivateKeyDialog dialog = new ExportPrivateKeyDialog(this);
//        dialog.setTitleTextView("创建成功");
//        dialog.setTips("备份提示：由于区块链的去中心化特性，EOS账号一旦丢失将无法找回。\\n请妥善备份您的私钥，以防账号丢失带来的损失。");
//        dialog.setMessage(privateKey);
//        dialog.setOnButtonClickListener(new ExportPrivateKeyDialog.OnButtonClickListener() {
//            @Override
//            public void onclick(int position) {
//                account.setEnable(true);
//                accountDao.insertOrReplace(account);
//                ClipboardManager cm = (ClipboardManager) AppContext.getInstance().getSystemService(Context.CLIPBOARD_SERVICE);
//                // 将文本内容放到系统剪贴板里。
//                cm.setText(privateKey);
//                ToastUtil.showToast(CreateEosWalletActivity.this, "已复制账户到剪切板");
//                dialog.dismiss();
//                finishAffinity();
//
//            }
//        });
//        dialog.show();
//    }

    /**
     * 创建分享二维码图片
     */
    private void shareImage() {
        CommonThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap bitmap = Bitmap.createBitmap(scrollContent.getWidth(), scrollContent.getHeight(), Bitmap.Config.RGB_565);
                    Canvas canvas = new Canvas(bitmap);
                    scrollContent.layout(scrollContent.getLeft(), scrollContent.getTop(), scrollContent.getRight(), scrollContent.getBottom());
                    scrollContent.draw(canvas);
                    String fileName = String.valueOf(TimeUtils.getNowMills());
                    ImageUtil.saveMyBitmap(CreateEosWalletActivity.this, fileName, bitmap);
                    SystemShareHelper.shareOneImage(CreateEosWalletActivity.this, ImageUtil.CHATPICTRE + fileName + ".png");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void sendToFriend() {
        Map<String, Object> map = new HashMap<>();
        String imgUrl = "https://panserver.solarsource.cn/panserver/files/7d9b9e9f-3242-468f-8077-89432080171b/download";
        map.put("title", "EOS");
        map.put("image", imgUrl);
        map.put("smallIcon", imgUrl);
        map.put("time", TimeUtils.getNowString());
        map.put("content", ResStringUtil.getString(R.string.open_planet_eos_create_request));
        map.put("systemName", "EOS");
        map.put("AndroidShow", "com.pansoft.openplanet.activity.child.HelpCreateEosFragment");
        map.put("show", "EOSCreateController");
        map.put("viewType", "display");
        map.put("eosActivePublicKey", mAccount_active_public_key);
        map.put("eosOwnerPublicKey", mAccount_owner_public_key);
        map.put("eosAccountName", accountName);
        net.sf.json.JSONObject jsonObject1 = net.sf.json.JSONObject.fromObject(map);
        IMStruct002 imStruct002 = new IMStruct002();
        try {
            imStruct002.setBody(jsonObject1.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        long currenttime = new Date().getTime();
        imStruct002.setTime(currenttime);
        imStruct002.setFromUserId(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        imStruct002.setMessageChildType(MessageChildTypeConstant.subtype_common);
        Intent intent = new Intent(this, MobileShareActivity.class);
        intent.putExtra("sendImStruct002", true);
        intent.putExtra("imStruct002", imStruct002);
        intent.putExtra("shareExplain", ResStringUtil
                .getString(R.string.open_planet_eos_create_request_short));

        startActivity(intent);
    }

    private void showPassDialog() {
        PassWordAlertDialog dialog = new PassWordAlertDialog(CreateEosWalletActivity.this,
                new PassWordAlertDialog.OnEnterClick() {
                    @Override
                    public void passVerifySuccess(String passWord) {
                        TCLoadingDataView.show(CreateEosWalletActivity.this,
                                ResStringUtil.getString(R.string.open_planet_generating_private_key));
                        TCAccountManager tcAccountManager = new TCAccountManager(CreateEosWalletActivity.this);
                        tcAccountManager.addEosWallet(account, accountDao.getMainAccountInDb(), new TCAccountManager.AccountManagerListener() {
                            @Override
                            public void onSuccess(Object object) {
                                account.setEnable(true);
                                accountDao.insertOrReplace(account);
                                TCLoadingDataView.dismiss();
                                ToastUtils.showShort(R.string.open_planet_create_success);
                            }

                            @Override
                            public void onFail(String fail) {
                                TCLoadingDataView.dismiss();
                                ToastUtils.showShort(R.string.open_planet_create_fail_please_retry);
                            }
                        });
                    }
                });
        dialog.setCanCancle(false);
        dialog.show();
    }
}
